//
//  MusicViewController.m
//  OurRelax
//
//  Created by 于宾尧 on 15/6/16.
//  Copyright (c) 2015年 于宾尧. All rights reserved.
//

#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define GapOfImage 10.0

#import "MusicViewController.h"
#import <MJRefresh.h>
#import "MusicCollectionViewCell.h"
#import "FirstMusicCollectionViewCell.h"
#import "MusicDetailShareHandle.h"

#import "MusicDetailViewController.h"

#import "AFNConnect.h"

@interface MusicViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (retain, nonatomic) UICollectionViewFlowLayout *myFlow;
@property (retain, nonatomic) UICollectionView *myCollection;

@property (retain, nonatomic) NSIndexPath *indexPath;

@property (retain, nonatomic) FirstMusicCollectionViewCell *firstC;

@property (nonatomic, copy) NSString *songID;
@property (nonatomic, retain) NSMutableArray *songListArray;

//获取week
@property (nonatomic, retain) NSMutableArray *weekArray;
@property (nonatomic, retain) NSMutableArray *weekIntArray;

//下一界面的详细界面
@property (nonatomic, retain) MusicDetailModel *nextMusicDetail;

//上拉，下拉
@property(nonatomic, assign) NSInteger nextPage;  //记录下一页
@property(nonatomic, assign) BOOL isUpLoading;    //标记上拉操作还是下拉操作，yes为上拉

@end

@implementation MusicViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        self.musicArray = [NSMutableArray array];
        self.musicDetailArray = [NSMutableArray array];
        self.weekArray = [NSMutableArray array];
        
        self.nextMusicDetail = [[MusicDetailModel alloc] init];
        self.isUpLoading = NO;
        
        _myFlow = [[UICollectionViewFlowLayout alloc] init];
        _myFlow.headerReferenceSize = CGSizeMake(0, 50);
        //_myFlow.footerReferenceSize = CGSizeMake(50, 350);
        
        if ([[UIScreen mainScreen] bounds].size.width == 375) {
            
            _myFlow.itemSize = CGSizeMake(120, 140);
            _myFlow.sectionInset = UIEdgeInsetsMake(10, 40, 1, 40);
            
        } else if ([[ UIScreen mainScreen] bounds].size.width > 375) {
        
            _myFlow.itemSize = CGSizeMake(120, 140);
            _myFlow.sectionInset = UIEdgeInsetsMake(10, 60, 1, 60);
        } else {
        
            _myFlow.itemSize = CGSizeMake(([[UIScreen mainScreen] bounds].size.width - 50) / 2.0, ([[UIScreen mainScreen] bounds].size.width - 50) / 2.0 + 10);
            _myFlow.sectionInset = UIEdgeInsetsMake(10, 10, 1, 10);
        }
        _myFlow.minimumLineSpacing = 20.0;
        _myFlow.minimumInteritemSpacing = 20.0;
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor blueColor];
    //UIColor *backC = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroud_hudie2.jpg"]];
    //self.view.backgroundColor = backC;
    
    self.myCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 49) collectionViewLayout:_myFlow];
    _myCollection.dataSource = self;
    _myCollection.delegate = self;
    _myCollection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myCollection];
    [_myCollection release];
    
    [_myCollection registerClass:[FirstMusicCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [_myCollection registerClass:[MusicCollectionViewCell class] forCellWithReuseIdentifier:@"music"];
    
    [_myCollection  registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerReuse"];
    [_myCollection  registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"weekHeaderReuse"];
    
    [self addHeader];
    [self addFooter];
}

//从网络获取 —— 精选
-(void)getSingles
{
    [AFNConnect AFNConnectWithUrl:@"http://online.dongting.com/recomm/new_songs_more?page=1&size=30&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=be1f25173f9be5d1454353a8fc39c8659b1c8f50&idfa=63406252-6848-4643-9CB3-2BC90F4A311D&utdid=VXllpMbdd2oDABsdVak%2BsCvi&alf=201200&bundle_id=com.ttpod.music" key:@"singles" connectBlock:^(id data) {
        
        self.musicArray = [MusicModel musicWithArray:data];
        
        //单例 获取musicModel
        [MusicDetailShareHandle shareListDataHandle].messageArray = self.musicArray;
        NSLog(@"====== %@",self.musicArray);
        
        [self.myCollection reloadData];
        [self.myCollection.header endRefreshing];
    }];
}

//从网络获取 —— 新歌一级
-(void)getData:(NSInteger)nextPage
{
    NSString *urlStr = [NSString stringWithFormat:@"http://online.dongting.com/recomm/new_songs_more?page=%ld&size=30&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=be1f25173f9be5d1454353a8fc39c8659b1c8f50&idfa=63406252-6848-4643-9CB3-2BC90F4A311D&utdid=VXllpMbdd2oDABsdVak%%2BsCvi&alf=201200&bundle_id=com.ttpod.music", nextPage];
    
    [AFNConnect AFNConnectWithUrl:urlStr key:@"data" connectBlock:^(id data) {
        
        //NSLog(@"%2C");
        if (!_isUpLoading) {
            
            [self.musicDetailArray removeAllObjects];
            self.musicWeekDic = [NSMutableDictionary dictionary];
        }
        NSMutableArray *array = [MusicModel musicWithArray:data];
        for (MusicModel *tmp in array) {
            
            [self.musicDetailArray addObject:tmp];
        }
        //self.musicDetailArray;
        //NSLog(@"-=-=-=-=- %@",_musicDetailArray);
        
        MusicModel *tmpMusic = [self.musicDetailArray firstObject];
        //NSLog(@"dfsf %@ %@", tmpMusic, tmpMusic.week);
        NSString *weekTag = [tmpMusic.week description];
        //NSLog(@"week = %@", weekTag);
        //NSLog(@"sdfsdsssss %@", self.musicDetailArray);
        
        /*
        for (MusicModel *tmp in self.musicDetailArray) {
            
            //NSLog(@"%@ %@", tmp.week, weekTag);
            if ([tmp.week isEqual:weekTag]) {
                
                [self.weekArray addObject:tmp];
                //NSLog(@"equal = %@, %@", _musicWeekDic, tmp.week);
            
            } else {
            
                weekTag = tmp.week;
                self.weekArray = [NSMutableArray array];
                [self.weekArray addObject:tmp];
            }
            [self.musicWeekDic setObject:self.weekArray forKey:weekTag];
        }*/
        
        // ************************ 排序 ***************************
        //NSLog(@"%ld",[weekTag integerValue]);
        self.weekIntArray = [NSMutableArray array];
        NSInteger weekTagInt = [weekTag integerValue];
        NSInteger minInt = weekTagInt;
        for (MusicModel *tmp in self.musicDetailArray) {
            
            NSInteger tmpInt = [tmp.week integerValue];
            minInt = minInt > tmpInt ? tmpInt : minInt;
            //NSLog(@"%ld",minInt);
            if (tmpInt != weekTagInt) {
                
                //[weekIntArray addObject:[NSString stringWithFormat:@"%ld", weekTagInt]];
                //NSLog(@"%ld",_weekIntArray.count);
                [self.weekIntArray insertObject:[NSString stringWithFormat:@"%ld", minInt] atIndex:_weekIntArray.count];
                weekTagInt = tmpInt;
                self.weekArray = [NSMutableArray array];
                [self.weekArray addObject:tmp];
                //NSLog(@"fdfdfdfdf %@", self.weekArray);
            } else {
            
                [self.weekArray addObject:tmp];
            }
            //NSLog(@"%@",_weekIntArray);
            [self.musicWeekDic setObject:self.weekArray forKey:[NSString stringWithFormat:@"%ld", minInt]];
            //NSLog(@"%@",_musicWeekDic);
        }
        //NSLog(@"sssss %@", _weekIntArray);
        [MusicDetailShareHandle shareListDataHandle].weekDic = self.musicWeekDic;
        [MusicDetailShareHandle shareListDataHandle].weekForDetailArray = self.weekIntArray;
        //NSLog(@"dfsf %@", weekArray);
        //NSLog(@"sdfsdf %@", self.musicWeekDic);
        
        [self.myCollection reloadData];
        [self.myCollection.header endRefreshing];
        [self.myCollection.footer endRefreshing];
        
    }];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.weekIntArray.count + 1;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        
        if (indexPath.section == 0) {
            
            UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerReuse" forIndexPath:indexPath];
            //headerView.backgroundColor = [UIColor clearColor];
            
            UILabel *newL = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, headerView.frame.size.height - 10, headerView.frame.size.height - 10)];
            newL.text = @"新";
            newL.textColor = [UIColor whiteColor];
            newL.layer.masksToBounds = YES;
            newL.layer.cornerRadius = 20;
            newL.textAlignment=YES;
            newL.font = [UIFont systemFontOfSize:25.0];
            newL.backgroundColor = [UIColor cyanColor];
            [headerView addSubview:newL];
            [newL release];
            
            UILabel *nextL = [[UILabel alloc] initWithFrame:CGRectMake(newL.frame.origin.x + newL.frame.size.width + 5, 10, 60, headerView.frame.size.height - 10)];
            nextL.text = @"精选";
            nextL.font = [UIFont systemFontOfSize:15.0];
            nextL.textColor = [UIColor darkGrayColor];
            [headerView addSubview:nextL];
            [nextL release];
            
            return headerView;
            
            
        } else {
        
            UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"weekHeaderReuse" forIndexPath:indexPath];
            //headerView.backgroundColor = [UIColor clearColor];
            
            UILabel *weekL = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, headerView.frame.size.height - 10, headerView.frame.size.height - 10)];
            //数据传值
            NSString *weekStr = [NSString stringWithFormat:@"%@/周", [self.weekIntArray objectAtIndex:indexPath.section - 1]];
            NSLog(@"33333 %@ %@",weekStr, self.weekIntArray);
            weekL.text = weekStr;
            weekL.backgroundColor = [UIColor colorWithRed:0.2 green:0.8 blue:0.2 alpha:1.0];
            weekL.font = [UIFont systemFontOfSize:15.0];
            weekL.textColor = [UIColor whiteColor];
            weekL.layer.masksToBounds = YES;
            weekL.layer.cornerRadius = 20;
            weekL.textAlignment = YES;
            [headerView addSubview:weekL];
            [weekL release];
            
            UILabel *yearL = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 130, 10, 120, headerView.frame.size.height - 20)];
            //数据传值
            NSString *yearStr = [NSString stringWithFormat:@"%@", @"2015"];
            yearL.text = yearStr;
            yearL.textColor = [UIColor darkGrayColor];
            yearL.textAlignment = NSTextAlignmentRight;
            [headerView addSubview:yearL];
            [yearL release];
            
            return headerView;
        }
        
    }
    return 0;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        
        return self.musicArray.count;
        
    } else {
    
        NSMutableArray *array = [NSMutableArray array];
        //NSString *weekKey = [self.musicWeekDic.allKeys objectAtIndex:section - 1];
        NSString *rightKey = [self.weekIntArray objectAtIndex:section - 1];
        for (NSString *tmp in self.musicWeekDic.allKeys) {
            
            if ([rightKey isEqualToString:tmp]) {
                
                
                array = [self.musicWeekDic objectForKey:tmp];
                
            }
        }
        //NSLog(@"%ld",array.count);
        return array.count;
        
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        //NSLog(@"11111111111%@",self.musicArray);
        _firstC = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        
        _firstC.firstMusic = [self.musicArray objectAtIndex:indexPath.row];
        
        return _firstC;
        
    } else {
    
        MusicCollectionViewCell *myMusicCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"music" forIndexPath:indexPath];
        
        //NSString *weekKey = [self.musicWeekDic.allKeys objectAtIndex:indexPath.section - 1];
        NSString *rightKey = [self.weekIntArray objectAtIndex:indexPath.section - 1];
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *tmp in self.musicWeekDic.allKeys) {
            
            if ([rightKey isEqualToString:tmp]) {
                
                array = [self.musicWeekDic objectForKey:tmp];
            }
        }
        myMusicCell.newMusic = [array objectAtIndex:indexPath.row];
        
        return myMusicCell;
        
    }
}

// ********************************** push ****************************************
//没有navigationcontroller，所以要协议，让rootviewcontroller来做
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld %ld", (long)indexPath.section, (long)indexPath.row);
    
    //[MusicDetailShareHandle shareListDataHandle].nextPageIndexPath = indexPath;
    if (indexPath.section == 0) {
        
        //获取下一页id
        [MusicDetailShareHandle shareListDataHandle].playingMusic = (MusicModel *)self.musicArray[indexPath.row];
        [MusicDetailShareHandle shareListDataHandle].nextPageIndexPath = indexPath;
        //NSString *msgId = ((MusicModel *)self.musicArray[indexPath.row]).msg_id;
        //[[MusicDetailShareHandle shareListDataHandle] sendPlayingMusic:(MusicModel *)self.musicArray[indexPath.row]];
        //[self getSonglist:msgId indexPath:indexPath];
        [self.myDelegate pushToDetail];
    } else {
    
        //NSString *weekKey = [self.musicWeekDic.allKeys objectAtIndex:indexPath.section - 1];
        NSString *weekKey = [self.weekIntArray objectAtIndex:indexPath.section - 1];
        NSMutableArray *tmpArray = [self.musicWeekDic objectForKey:weekKey];
        
        //获取下一页id
        [MusicDetailShareHandle shareListDataHandle].playingMusic = (MusicModel *)tmpArray[indexPath.row];
        [MusicDetailShareHandle shareListDataHandle].nextPageIndexPath = indexPath;
        //NSString *msgId = ((MusicModel *)tmpArray[indexPath.row]).msg_id;
        //[[MusicDetailShareHandle shareListDataHandle] sendPlayingMusic:(MusicModel *)self.musicArray[indexPath.row]];
        //[self getSonglist:msgId indexPath:indexPath];
        [self.myDelegate pushToDetail];
    }
    
}

// ********************************** 上拉下拉 **********************************
//下拉
-(void)addHeader
{
    
    __block MusicViewController *musicVC = self; //因为block块里用self会报警告,所以需要将self声明成block变量
    
    self.myCollection.header =
    [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        musicVC.nextPage = 1;       //记录页码的
        musicVC.isUpLoading = NO;   //标记为下拉操作
        //[musicVC createDate:musicVC.nextPage];//重新请求数据
        [musicVC getSingles];
        [musicVC getData:_nextPage];
        
    }];
    
    [self.myCollection.header beginRefreshing];
}

#pragma mark —上拉加载更多
- (void)addFooter
{
    //      __unsafe_unretained typeof(self) vc = self;
    __block MusicViewController *vc = self;
    
    
    self.myCollection.footer = [MJRefreshAutoNormalFooter  footerWithRefreshingBlock:^{
        vc.nextPage ++;
        vc.isUpLoading = YES;       //标记为上拉操作
        //[vc createDate:vc.nextPage];//请求数据
        [vc getData:_nextPage];
        
    }];
    
    
}

/*
// ********************************** 获取下一页面id **********************************
//获取下一界面的id
-(void)getSonglist:(NSString *)songID indexPath:(NSIndexPath *)indexPath;
{
    NSMutableArray *songIDArray = [NSMutableArray array];
    //NSLog(@"232323 %@",self.nextId);
    NSString *urlStr = [NSString stringWithFormat:@"http://v1.ard.q.itlily.com/share/user_timeline?msg_ids=%%5B%@%%5D&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone7%%2C2&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=0dd348dbab822aeed85fbb8aa4c013f995b389ff&idfa=40C53D22-7D7E-4CE4-B53C-647128B9A9EA&utdid=VXlbm0s4gVcDAKj0hGWGx2OY&alf=201200&bundle_id=com.ttpod.music", songID];
    //NSLog(@"dfsdfsdfseee  %@", urlStr);
    [AFNConnect AFNConnectWithUrl:urlStr key:@"data" connectBlock:^(id data) {
        
        //NSLog(@"====== %@",data);
        self.nextMusicDetail = (MusicDetailModel *)[MusicDetailModel musicDetailWithArray:data];
        //NSLog(@"454545454 %@", _nextMusicDetail.pics);
        
        for (NSMutableDictionary *dic in (NSMutableArray *)_nextMusicDetail.songlist) {
            
            [songIDArray addObject:[dic objectForKey:@"song_id"]];
            
        }
        //NSLog(@"67676767=%ld",songIDArray.count);
        
        NSString *tmp = songIDArray[0];
        for (int i = 1; i < songIDArray.count; i++) {
            
            self.songID = [NSString stringWithFormat:@"%@,%@", tmp, songIDArray[i]];
            tmp = _songID;
            
        }
        //NSLog(@"%@", _songID);
        
        [self getSongData:indexPath];
    }];
    
}

-(void)getSongData:(NSIndexPath *)indexPath
{
    NSString *urlStr = [NSString stringWithFormat:@"http://ting.hotchanson.com/songs/downwhite?song_id=%@&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone7%%2C2&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=0dd348dbab822aeed85fbb8aa4c013f995b389ff&idfa=40C53D22-7D7E-4CE4-B53C-647128B9A9EA&utdid=VXlbm0s4gVcDAKj0hGWGx2OY&alf=201200&bundle_id=com.ttpod.music", self.songID];
    
    [AFNConnect AFNConnectWithUrl:urlStr key:@"data" connectBlock:^(id data) {
        
        //NSLog(@"DetailData = %@", data);
        self.songListArray = [MusicForSonglist songListWithArray:data];
        //NSLog(@"songList = %@", _songListArray);
        
        [[MusicDetailShareHandle shareListDataHandle] sendSongListModel:_songListArray];
        //NSLog(@"dfsdfdf %@",[MusicDetailShareHandle shareListDataHandle].listShareArray);
        
        if (indexPath.section == 0) {
            
            NSString *detailTitle = ((MusicModel *)self.musicArray[indexPath.row]).title;
            
            //NSLog(@"%ld",indexPath.row);
            [self.myDelegate pushToDetail:detailTitle andArray:self.songListArray andDetailModel:self.nextMusicDetail];
            //NSLog(@"songlistArray = %@",self.songListArray);
            
        } else {
            
            NSString *weekKey = [self.musicWeekDic.allKeys objectAtIndex:indexPath.section - 1];
            NSMutableArray *tmpArray = [self.musicWeekDic objectForKey:weekKey];
            //NSLog(@"tmpArray = %@", tmpArray);
            NSString *songTitle = ((MusicModel *)tmpArray[indexPath.row]).title;
            [self.myDelegate pushToDetail:songTitle andArray:self.songListArray andDetailModel:self.nextMusicDetail];
            //NSLog(@"songlistArray = %@",self.songListArray);
        }
        
    }];
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
